package cc.yaomm.service.basic.manager;

import cc.yaomm.common.basic.util.BeanUtils;
import cc.yaomm.common.biz.enums.ServeTypeEnum;
import cc.yaomm.common.biz.lang.bo.ResourceBO;
import cc.yaomm.service.basic.entity.user.Resources;
import cc.yaomm.service.basic.mapper.user.ResourcesMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class ResourceManager {

    @Autowired
    private ResourcesMapper resourcesMapper;

    /**
     * <p>@Description : 刷新资源</p>
     * <p>@Author : QiLin.Xing </p>
     * <p>@Date : 2019/3/15 14:10 </p>
     */
    @Transactional
    public boolean refresh(ServeTypeEnum serveName, Collection<ResourceBO> resourceList) {
        if (CollectionUtils.isEmpty(resourceList)) {
            return false;
        }

        //查询所有的资源
        LambdaQueryWrapper<Resources> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resources::getOwnerServe, serveName.getValue());
        Map<String, Resources> resourceMap = resourcesMapper.findOfMap(wrapper, Resources::getCode);
        //新增或者更新集合
        List<Resources> updateList = new ArrayList<>();
        //遍历现有资源集合
        for (ResourceBO resourceBO : resourceList) {
            Resources resources = resourceMap.get(resourceBO.getCode());
            if (Objects.nonNull(resources)) {
                resourceMap.remove(resources.getCode());
                org.springframework.beans.BeanUtils.copyProperties(resourceBO, resources);
            } else {
                resources = BeanUtils.map(resourceBO, Resources.class);
            }
            updateList.add(resources);
        }

        //清除废弃的资源
        if (!CollectionUtils.isEmpty(resourceMap)) {
            Set<Long> idSet = resourceMap.values().stream().map(Resources::getId).collect(Collectors.toSet());
            resourcesMapper.deleteBatchIds(idSet);
        }

        //更新或添加资源
        return resourcesMapper.batchInsertOrUpdate(updateList);
    }

}
